import React, { useState, useEffect } from 'react';
import { 
  MegaphoneIcon, 
  ExclamationTriangleIcon, 
  InformationCircleIcon,
  CalendarIcon,
  UserIcon,
  ClockIcon,
  DocumentTextIcon,
  WrenchScrewdriverIcon,
  BellIcon,
  ShieldExclamationIcon,
  PencilIcon,
  PlusIcon,
  XMarkIcon
} from '@heroicons/react/24/outline';
import { Announcement, UserRole } from '../shared/types';

type Props = {
  currentUser?: any;
}

const Announcements = ({ currentUser }: Props) => {
  const [announcements, setAnnouncements] = useState<Announcement[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [filterType, setFilterType] = useState<'all' | 'notice' | 'maintenance' | 'event' | 'policy' | 'emergency'>('all');
  const [filterPriority, setFilterPriority] = useState<'all' | 'low' | 'medium' | 'high' | 'urgent'>('all');
  const [showEditModal, setShowEditModal] = useState(false);
  const [editingAnnouncement, setEditingAnnouncement] = useState<Announcement | null>(null);
  const [showAddModal, setShowAddModal] = useState(false);

  // 模拟公告数据
  useEffect(() => {
    const mockAnnouncements: Announcement[] = [
      {
        id: '1',
        title: '健身房开放时间调整通知',
        content: '由于期末考试期间，健身房开放时间调整为：周一至周五 6:00-22:00，周末 8:00-20:00。请同学们合理安排锻炼时间。',
        type: 'notice',
        priority: 'high',
        isActive: true,
        isPinned: true,
        author: '健身房管理员',
        createdAt: '2024-09-20',
        updatedAt: '2024-09-20',
        publishDate: '2024-09-20',
        expireDate: '2024-12-31'
      },
      {
        id: '2',
        title: '跑步机维护通知',
        content: '健身房1-3号跑步机将于9月25日-9月27日进行定期维护，期间暂停使用。请同学们使用其他跑步机或选择其他有氧运动。',
        type: 'maintenance',
        priority: 'medium',
        isActive: true,
        isPinned: false,
        author: '设备管理员',
        createdAt: '2024-09-22',
        updatedAt: '2024-09-22',
        publishDate: '2024-09-22',
        expireDate: '2024-09-27'
      },
      {
        id: '3',
        title: '2024年秋季健身大赛报名开始',
        content: '海大健身房2024年秋季健身大赛即将开始！比赛项目包括：引体向上、俯卧撑、平板支撑、跑步等。报名时间：9月20日-10月10日。',
        type: 'event',
        priority: 'high',
        isActive: true,
        isPinned: true,
        author: '活动组织者',
        createdAt: '2024-09-19',
        updatedAt: '2024-09-19',
        publishDate: '2024-09-19',
        expireDate: '2024-10-15'
      },
      {
        id: '4',
        title: '健身房安全使用须知',
        content: '为了保障同学们的安全，请在使用健身器材前仔细阅读使用说明，正确使用护具，如有疑问请咨询现场工作人员。',
        type: 'policy',
        priority: 'medium',
        isActive: true,
        isPinned: false,
        author: '安全管理员',
        createdAt: '2024-09-15',
        updatedAt: '2024-09-15',
        publishDate: '2024-09-15'
      },
      {
        id: '5',
        title: '紧急通知：健身房临时关闭',
        content: '由于电路检修，健身房将于9月24日 14:00-18:00 临时关闭。请同学们提前安排锻炼时间，给您带来的不便敬请谅解。',
        type: 'emergency',
        priority: 'urgent',
        isActive: true,
        isPinned: true,
        author: '健身房管理员',
        createdAt: '2024-09-23',
        updatedAt: '2024-09-23',
        publishDate: '2024-09-23',
        expireDate: '2024-09-24'
      },
      {
        id: '6',
        title: '新器材使用培训通知',
        content: '健身房新增了一批专业健身器材，将于9月28日 15:00 在健身房举办使用培训，欢迎同学们参加。',
        type: 'notice',
        priority: 'low',
        isActive: true,
        isPinned: false,
        author: '培训师',
        createdAt: '2024-09-21',
        updatedAt: '2024-09-21',
        publishDate: '2024-09-21',
        expireDate: '2024-09-28'
      }
    ];
    
    setTimeout(() => {
      setAnnouncements(mockAnnouncements);
      setIsLoading(false);
    }, 1000);
  }, []);

  const filteredAnnouncements = announcements.filter(announcement => {
    const typeMatch = filterType === 'all' || announcement.type === filterType;
    const priorityMatch = filterPriority === 'all' || announcement.priority === filterPriority;
    return typeMatch && priorityMatch;
  });

  const isAdmin = currentUser && (currentUser.role === UserRole.ADMIN || currentUser.role === UserRole.SUPER_ADMIN);

  const handleEditAnnouncement = (announcement: Announcement) => {
    setEditingAnnouncement(announcement);
    setShowEditModal(true);
  };

  const handleAddAnnouncement = () => {
    setEditingAnnouncement(null);
    setShowAddModal(true);
  };

  const handleSaveAnnouncement = (announcementData: Partial<Announcement>) => {
    if (editingAnnouncement) {
      // 编辑现有公告
      setAnnouncements(prev => prev.map(ann => 
        ann.id === editingAnnouncement.id 
          ? { ...ann, ...announcementData, updatedAt: new Date().toISOString().split('T')[0] }
          : ann
      ));
    } else {
      // 添加新公告
      const newAnnouncement: Announcement = {
        id: Date.now().toString(),
        title: announcementData.title || '',
        content: announcementData.content || '',
        type: announcementData.type || 'notice',
        priority: announcementData.priority || 'medium',
        isActive: true,
        isPinned: announcementData.isPinned || false,
        author: currentUser?.name || '管理员',
        createdAt: new Date().toISOString().split('T')[0],
        updatedAt: new Date().toISOString().split('T')[0],
        publishDate: new Date().toISOString().split('T')[0],
        expireDate: announcementData.expireDate
      };
      setAnnouncements(prev => [newAnnouncement, ...prev]);
    }
    setShowEditModal(false);
    setShowAddModal(false);
    setEditingAnnouncement(null);
  };

  const getTypeIcon = (type: string) => {
    switch (type) {
      case 'notice': return <MegaphoneIcon className="w-5 h-5" />;
      case 'maintenance': return <WrenchScrewdriverIcon className="w-5 h-5" />;
      case 'event': return <CalendarIcon className="w-5 h-5" />;
      case 'policy': return <DocumentTextIcon className="w-5 h-5" />;
      case 'emergency': return <ShieldExclamationIcon className="w-5 h-5" />;
      default: return <InformationCircleIcon className="w-5 h-5" />;
    }
  };

  const getTypeText = (type: string) => {
    switch (type) {
      case 'notice': return '通知';
      case 'maintenance': return '维护';
      case 'event': return '活动';
      case 'policy': return '政策';
      case 'emergency': return '紧急';
      default: return '公告';
    }
  };

  const getTypeColor = (type: string) => {
    switch (type) {
      case 'notice': return 'bg-blue-100 text-blue-800';
      case 'maintenance': return 'bg-yellow-100 text-yellow-800';
      case 'event': return 'bg-green-100 text-green-800';
      case 'policy': return 'bg-purple-100 text-purple-800';
      case 'emergency': return 'bg-red-100 text-red-800';
      default: return 'bg-gray-100 text-gray-800';
    }
  };

  const getPriorityColor = (priority: string) => {
    switch (priority) {
      case 'low': return 'bg-gray-100 text-gray-800';
      case 'medium': return 'bg-blue-100 text-blue-800';
      case 'high': return 'bg-orange-100 text-orange-800';
      case 'urgent': return 'bg-red-100 text-red-800';
      default: return 'bg-gray-100 text-gray-800';
    }
  };

  const getPriorityText = (priority: string) => {
    switch (priority) {
      case 'low': return '低';
      case 'medium': return '中';
      case 'high': return '高';
      case 'urgent': return '紧急';
      default: return '普通';
    }
  };

  if (isLoading) {
    return (
      <div className="flex justify-center items-center h-64">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary"></div>
      </div>
    );
  }

  return (
    <div className="container mx-auto px-4 py-8">
      {/* 页面标题 */}
      <div className="mb-8">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-3">
            <MegaphoneIcon className="w-8 h-8 text-primary" />
            <h1 className="text-3xl font-bold text-gray-900">公告中心</h1>
          </div>
          {isAdmin && (
            <button
              onClick={handleAddAnnouncement}
              className="flex items-center gap-2 bg-primary text-white px-4 py-2 rounded-lg hover:bg-primary-300 transition-colors"
            >
              <PlusIcon className="w-5 h-5" />
              发布公告
            </button>
          )}
        </div>
        <p className="text-gray-600 mt-2">
          查看健身房最新通知、维护公告、活动信息等重要消息
        </p>
      </div>

      {/* 筛选栏 */}
      <div className="bg-white rounded-lg shadow-sm border p-6 mb-6">
        <div className="flex flex-col md:flex-row md:items-center gap-4">
          <div className="flex items-center gap-4">
            <label className="text-sm font-medium text-gray-700">类型筛选：</label>
            <select
              value={filterType}
              onChange={(e) => setFilterType(e.target.value as any)}
              className="px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-primary focus:border-transparent"
            >
              <option value="all">全部</option>
              <option value="notice">通知</option>
              <option value="maintenance">维护</option>
              <option value="event">活动</option>
              <option value="policy">政策</option>
              <option value="emergency">紧急</option>
            </select>
          </div>
          
          <div className="flex items-center gap-4">
            <label className="text-sm font-medium text-gray-700">优先级：</label>
            <select
              value={filterPriority}
              onChange={(e) => setFilterPriority(e.target.value as any)}
              className="px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-primary focus:border-transparent"
            >
              <option value="all">全部</option>
              <option value="urgent">紧急</option>
              <option value="high">高</option>
              <option value="medium">中</option>
              <option value="low">低</option>
            </select>
          </div>
        </div>
      </div>

      {/* 公告列表 */}
      <div className="space-y-4">
        {filteredAnnouncements.map((announcement) => (
          <div 
            key={announcement.id} 
            className={`bg-white rounded-lg shadow-sm border hover:shadow-md transition-shadow ${
              announcement.isPinned ? 'border-l-4 border-l-primary' : ''
            }`}
          >
            <div className="p-6">
              <div className="flex items-start justify-between mb-4">
                <div className="flex-1">
                  <div className="flex items-center gap-3 mb-2">
                    {announcement.isPinned && (
                      <BellIcon className="w-5 h-5 text-primary" title="置顶公告" />
                    )}
                    <h3 className="text-lg font-semibold text-gray-900">{announcement.title}</h3>
                  </div>
                  
                  <div className="flex items-center gap-4 mb-3">
                    <div className={`inline-flex items-center gap-1 px-2 py-1 text-xs font-medium rounded-full ${getTypeColor(announcement.type)}`}>
                      {getTypeIcon(announcement.type)}
                      {getTypeText(announcement.type)}
                    </div>
                    <div className={`inline-flex px-2 py-1 text-xs font-medium rounded-full ${getPriorityColor(announcement.priority)}`}>
                      {getPriorityText(announcement.priority)}优先级
                    </div>
                  </div>
                </div>
                
                {isAdmin && (
                  <button
                    onClick={() => handleEditAnnouncement(announcement)}
                    className="text-blue-600 hover:text-blue-900 p-1"
                    title="编辑公告"
                  >
                    <PencilIcon className="w-5 h-5" />
                  </button>
                )}
              </div>
              
              <div className="mb-4">
                <p className="text-gray-700 leading-relaxed whitespace-pre-line">
                  {announcement.content}
                </p>
              </div>
              
              <div className="flex items-center justify-between pt-4 border-t border-gray-100">
                <div className="flex items-center gap-6 text-sm text-gray-500">
                  <div className="flex items-center gap-1">
                    <UserIcon className="w-4 h-4" />
                    <span>{announcement.author}</span>
                  </div>
                  <div className="flex items-center gap-1">
                    <ClockIcon className="w-4 h-4" />
                    <span>发布时间: {announcement.publishDate}</span>
                  </div>
                  {announcement.expireDate && (
                    <div className="flex items-center gap-1">
                      <CalendarIcon className="w-4 h-4" />
                      <span>有效期至: {announcement.expireDate}</span>
                    </div>
                  )}
                </div>
              </div>
            </div>
          </div>
        ))}
      </div>

      {filteredAnnouncements.length === 0 && (
        <div className="text-center py-12">
          <MegaphoneIcon className="mx-auto h-12 w-12 text-gray-400" />
          <h3 className="mt-2 text-sm font-medium text-gray-900">没有找到公告</h3>
          <p className="mt-1 text-sm text-gray-500">
            {filterType !== 'all' || filterPriority !== 'all' 
              ? '尝试调整筛选条件' 
              : '暂时没有公告'}
          </p>
        </div>
      )}

      {/* 统计信息 */}
      <div className="mt-8 grid grid-cols-1 md:grid-cols-5 gap-4">
        <div className="bg-white p-4 rounded-lg border text-center">
          <div className="text-2xl font-bold text-gray-900">{announcements.length}</div>
          <div className="text-sm text-gray-500">总公告数</div>
        </div>
        <div className="bg-white p-4 rounded-lg border text-center">
          <div className="text-2xl font-bold text-blue-600">
            {announcements.filter(a => a.type === 'notice').length}
          </div>
          <div className="text-sm text-gray-500">通知</div>
        </div>
        <div className="bg-white p-4 rounded-lg border text-center">
          <div className="text-2xl font-bold text-yellow-600">
            {announcements.filter(a => a.type === 'maintenance').length}
          </div>
          <div className="text-sm text-gray-500">维护</div>
        </div>
        <div className="bg-white p-4 rounded-lg border text-center">
          <div className="text-2xl font-bold text-green-600">
            {announcements.filter(a => a.type === 'event').length}
          </div>
          <div className="text-sm text-gray-500">活动</div>
        </div>
        <div className="bg-white p-4 rounded-lg border text-center">
          <div className="text-2xl font-bold text-red-600">
            {announcements.filter(a => a.priority === 'urgent').length}
          </div>
          <div className="text-sm text-gray-500">紧急</div>
        </div>
      </div>

      {/* 编辑/添加公告模态框 */}
      {(showEditModal || showAddModal) && (
        <AnnouncementModal
          announcement={editingAnnouncement}
          onSave={handleSaveAnnouncement}
          onClose={() => {
            setShowEditModal(false);
            setShowAddModal(false);
            setEditingAnnouncement(null);
          }}
        />
      )}
    </div>
  );
};

// 公告编辑模态框组件
const AnnouncementModal = ({ 
  announcement, 
  onSave, 
  onClose 
}: { 
  announcement: Announcement | null;
  onSave: (data: Partial<Announcement>) => void;
  onClose: () => void;
}) => {
  const [formData, setFormData] = useState({
    title: announcement?.title || '',
    content: announcement?.content || '',
    type: announcement?.type || 'notice',
    priority: announcement?.priority || 'medium',
    isPinned: announcement?.isPinned || false,
    expireDate: announcement?.expireDate || ''
  });

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    onSave(formData);
  };

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
    const { name, value, type } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: type === 'checkbox' ? (e.target as HTMLInputElement).checked : value
    }));
  };

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div className="bg-white rounded-lg p-6 w-full max-w-2xl max-h-[90vh] overflow-y-auto">
        <div className="flex items-center justify-between mb-4">
          <h2 className="text-xl font-bold text-gray-900">
            {announcement ? '编辑公告' : '发布公告'}
          </h2>
          <button
            onClick={onClose}
            className="text-gray-400 hover:text-gray-600"
          >
            <XMarkIcon className="w-6 h-6" />
          </button>
        </div>

        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              标题 *
            </label>
            <input
              type="text"
              name="title"
              value={formData.title}
              onChange={handleInputChange}
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-primary focus:border-transparent"
              required
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              内容 *
            </label>
            <textarea
              name="content"
              value={formData.content}
              onChange={handleInputChange}
              rows={6}
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-primary focus:border-transparent"
              required
            />
          </div>

          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                类型 *
              </label>
              <select
                name="type"
                value={formData.type}
                onChange={handleInputChange}
                className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-primary focus:border-transparent"
              >
                <option value="notice">通知</option>
                <option value="maintenance">维护</option>
                <option value="event">活动</option>
                <option value="policy">政策</option>
                <option value="emergency">紧急</option>
              </select>
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                优先级 *
              </label>
              <select
                name="priority"
                value={formData.priority}
                onChange={handleInputChange}
                className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-primary focus:border-transparent"
              >
                <option value="low">低</option>
                <option value="medium">中</option>
                <option value="high">高</option>
                <option value="urgent">紧急</option>
              </select>
            </div>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              有效期至
            </label>
            <input
              type="date"
              name="expireDate"
              value={formData.expireDate}
              onChange={handleInputChange}
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-primary focus:border-transparent"
            />
          </div>

          <div className="flex items-center">
            <input
              type="checkbox"
              name="isPinned"
              checked={formData.isPinned}
              onChange={handleInputChange}
              className="h-4 w-4 text-primary focus:ring-primary border-gray-300 rounded"
            />
            <label className="ml-2 block text-sm text-gray-700">
              置顶显示
            </label>
          </div>

          <div className="flex justify-end gap-3 pt-4">
            <button
              type="button"
              onClick={onClose}
              className="px-4 py-2 text-gray-700 bg-gray-200 rounded-md hover:bg-gray-300 transition-colors"
            >
              取消
            </button>
            <button
              type="submit"
              className="px-4 py-2 bg-primary text-white rounded-md hover:bg-primary-300 transition-colors"
            >
              {announcement ? '保存' : '发布'}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
};

export default Announcements; 